package edu.ccut.titan.tag.report.exporter;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.ccut.titan.tag.report.servlet.IReportExporter;


import net.sf.jasperreports.engine.JRAbstractExporter;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperPrint;


public abstract class AbstractReportExporter implements IReportExporter {

	protected abstract void setContentType(HttpServletResponse response);
	
	protected abstract JRAbstractExporter creatExporter();
	
	protected void setParameters(JRAbstractExporter exporter, HttpServletRequest request, HttpServletResponse response) {
		
	}
	
	protected void morePrint(JasperPrint print, HttpServletRequest request, HttpServletResponse response, OutputStream outputStream) throws IOException {
		
	}
	
	protected OutputStream getOutputStream(HttpServletRequest request, HttpServletResponse response) throws IOException  {
		return response.getOutputStream();
	}
	
	public final void export(JasperPrint print, HttpServletRequest request, HttpServletResponse response) {
		this.setContentType(response);
		
		JRAbstractExporter exporter = this.creatExporter();

		OutputStream out = null;
		try {
			out = this.getOutputStream(request, response);
			this.setParameters(exporter, request, response);
			
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
			exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
			exporter.exportReport();
			
			this.morePrint(print, request, response, out);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JRException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.flush();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}
